package com.example.bluetooth.le;

import com.brtbeacon.sdk.BRTBeacon;
import com.brtbeacon.sdk.BRTBeaconConnection;
import com.brtbeacon.sdk.BRTThrowable;
import com.brtbeacon.sdk.Hardware;
import com.brtbeacon.sdk.IBle;
import com.brtbeacon.sdk.Utils;
import com.brtbeacon.sdk.callback.BRTBeaconConnectionListener;
import com.brtbeacon.sdk.callback.BRTBeaconFirmWareUpdateListener;
import com.brtbeacon.sdk.callback.BRTBeaconUpdateListener;
import com.brtbeacon.sdk.callback.WriteCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Beacon连接
 */
public class TestControlActivity extends Activity {
    private final static String TAG = TestControlActivity.class.getSimpleName();

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    private TextView mConnectionState;
    private TextView mValues;
    private String mDeviceName;
    private String mDeviceAddress;
    private boolean mConnected = false;
    protected IBle mBle;

    private BRTBeaconConnection beaconConnection;
    private BRTBeacon mBeacon;

    public static byte[] upload(byte msg_id, byte[] msg_data) {

        byte[] msg_a = new byte[msg_data.length + 2];
        msg_a[0] = msg_id;
        if (msg_data == null) {
            msg_a[1] = 0;
        } else {
            msg_a[1] = (byte) ((msg_data.length + 2) & 0xFF);
            System.arraycopy(msg_data, 0, msg_a, 2, msg_data.length);
        }

        return msg_a;
    }

    private byte[] createData() {
        byte[] value = new byte[8];
        byte[] majorBytes = Utils.inttobyte4(4484);// 0~65535
        // byte[] minorBytes = Utils.inttobyte(10001);// 0~65535
        // // System.arraycopy(uuidBytes, 0, value, 0, 16);
        System.arraycopy(majorBytes, 0, value, 4, 4);
        // System.arraycopy(minorBytes, 0, value, 2, 2);
        byte[] data = upload((byte) 0x08, value);// 800A0000000000001184
                                                 // 080a0000000000001184

        return data;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gatt_services_characteristics);
        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
        mBeacon = intent.getParcelableExtra("TAG");
        // Sets up UI references.
        ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);

        mConnectionState = (TextView) findViewById(R.id.connection_state);
        mValues = (TextView) findViewById(R.id.connection_values);
        findViewById(R.id.connection_values_write_uuid)
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (beaconConnection.isConnected()) {
                            // 设置参数
                            // BRTBeaconConfig config = new BRTBeaconConfig();
                            // config.setUuid("00000000000000000000000000000002");
                            // config.setMajor(1002);
                            // config.setMinor(1002);
                            // config.setName("2");
                            // config.setTxPower(BRTBeaconPower.BRTBeaconPowerLevelMinus4);
                            // config.setMeasuredPower(-66);
                            // config.setAdIntervalMillis(200);
                            // // 更新参数
                            // beaconConnection.writeValues(config);

                            beaconConnection.writeCharacteristicV3(createData(),
                                    new WriteCallback() {

                                @Override
                                public void onSuccess() {
                                    Toast.makeText(TestControlActivity.this,
                                            "写入成功", Toast.LENGTH_LONG).show();
                                }

                                @Override
                                public void onError(BRTThrowable throwable) {
                                    Toast.makeText(TestControlActivity.this,
                                            "写入失败", Toast.LENGTH_LONG).show();
                                }

                                @Override
                                public void onCharacteristicChanged(String uuid,
                                        byte[] value) {
                                    // TODO Auto-generated method stub

                                }
                            });
                        }
                    }
                });
        findViewById(R.id.connection_values_update_firm)
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (beaconConnection.isConnected()) {
                            // 检查固件是否可更新
                            beaconConnection.checkBeaconFirmWare(
                                    new BRTBeaconUpdateListener() {

                                @Override
                                public void onFirmWareUpdate(
                                        final Hardware hardware) {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            if (beaconConnection.isConnected()
                                                    && hardware
                                                            .isNeedUpdate()) {
                                                // 固件可更新，更新固件
                                                beaconConnection
                                                        .updateBeaconFirmWare(
                                                                hardware,
                                                                new BRTBeaconFirmWareUpdateListener() {

                                                    @Override
                                                    public void onProgress(
                                                            int progress,
                                                            int max) {
                                                        System.out.println(
                                                                "升级固件>>>>>"
                                                                        + progress
                                                                        + "/"
                                                                        + max);
                                                    }

                                                    @Override
                                                    public void onError(
                                                            BRTThrowable throwable) {
                                                        System.out.println(
                                                                "升级固件异常>>>>>");
                                                    }
                                                });
                                            } else {
                                                Toast.makeText(
                                                        TestControlActivity.this,
                                                        "当前是最新固件",
                                                        Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    }
                });

        getActionBar().setTitle(mDeviceName);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        BleApplication app = (BleApplication) getApplication();
        mBle = app.getIBle();
        beaconConnection = new BRTBeaconConnection(this, mBle, mBeacon,
                new BRTBeaconConnectionListener() {

                    @Override
                    public void onConnectedState(int newState, int status) {
                        // 连接状态 BRTBeaconConnection.CONNECTED or
                        // BRTBeaconConnection.DISCONNECTED
                        if (newState == BRTBeaconConnection.CONNECTED) {
                            Toast.makeText(TestControlActivity.this, "连接成功",
                                    Toast.LENGTH_LONG).show();
                            mConnected = true;
                            updateConnectionState(R.string.connected);
                            invalidateOptionsMenu();
                            beaconConnection.readBeacon();
                        } else {
                            Toast.makeText(TestControlActivity.this,
                                    "连接断开(" + status + ")", Toast.LENGTH_LONG)
                                    .show();
                            onDeviceDisconnected();
                        }
                    }

                    // @Override
                    // public void onAuthentication(BRTBeacon beacon) {
                    // // 验证APPKEY成功回调
                    // Toast.makeText(TestControlActivity.this, "APPKEY验证通过",
                    // Toast.LENGTH_SHORT).show();
                    //
                    // bindView(beacon);
                    // }
                    //
                    // @Override
                    // public void onUpdateBeaconSuccess(BRTBeacon beacon, int
                    // status) {
                    // // 更新Beacon参数
                    // Toast.makeText(TestControlActivity.this, "更新参数成功",
                    // Toast.LENGTH_SHORT).show();
                    //
                    // bindView(beacon);
                    // }

                    @Override
                    public void onError(BRTThrowable throwable) {
                        // TODO Auto-generated method stub
                        Toast.makeText(TestControlActivity.this,
                                throwable.getCode() + throwable.getError(),
                                Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onBeaconRead(BRTBeacon beacon) {
                        // TODO Auto-generated method stub
                        // Toast.makeText(TestControlActivity.this,
                        // beacon.toString(),
                        // Toast.LENGTH_LONG).show();
                        bindView(beacon);
                    }

                    @Override
                    public void onBeaconWrite(BRTBeacon beacon, int status) {
                        Toast.makeText(TestControlActivity.this, status + "",
                                Toast.LENGTH_LONG).show();
                        bindView(beacon);
                    }

                    @Override
                    public void onCharacteristicChanged(String uuid, int status,
                            byte[] value) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onCharacteristicWrite(String uuid, int status,
                            byte[] value) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onCharacteristicRead(String uuid, int status,
                            byte[] value) {
                        // TODO Auto-generated method stub

                    }

                });
    }

    private void bindView(BRTBeacon beacon) {
        mValues.setText(String.format(
                "name:%s\nuuid:%s\nmajor:%d\nminor:%d\ntxPower:%d\nmsPower:%d\nadvinterval:%d\nMode:%d\nBattery:%d\nTempt:%d\nLight:%d",
                beacon.getName(), beacon.getUuid(), beacon.getMajor(),
                beacon.getMinor(), beacon.getTxPower().ordinal(),
                beacon.getMeasuredPower(), beacon.getAdIntervalMillis(),
                beacon.getDeviceMode(), beacon.getBattery(),
                beacon.getTemperature(), beacon.getLight()));

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (beaconConnection != null) {
            // 断开连接
            beaconConnection.disconnect();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gatt_services, menu);
        if (mConnected) {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_connect:
                // 连接
                if (!beaconConnection.isConnected()) {
                    beaconConnection.connect();
                }

                return true;
            case R.id.menu_disconnect:
                beaconConnection.disconnect();
                onDeviceDisconnected();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mConnectionState.setText(resourceId);
            }
        });
    }

    private void onDeviceDisconnected() {
        mConnected = false;
        updateConnectionState(R.string.disconnected);
        invalidateOptionsMenu();
        clearUI();
    }

    private void clearUI() {
        // TODO Auto-generated method stub

    }
}
